//
//  DYRemoteControlViewController.m
//  DaYing
//
//  Created by DaYing Team on 2023.
//  Copyright © 2023 DaYing Team. All rights reserved.
//

#import "DYRemoteControlViewController.h"

#import <WebKit/WebKit.h>

#import "AFNetworking.h"

@interface DYRemoteControlViewController () <WKNavigationDelegate,WKScriptMessageHandler>

//webview,加载网页用。
@property (strong, nonatomic) WKWebView *webView;

@end

@implementation DYRemoteControlViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self setNavigationItemTitleViewWithTitle:@"遥控器"];
    self.navigationBar.hidden = YES;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        NSLog(@"延迟秒后打印出来的日志！");
        NSString *urlStr = kRemoteControlUrl;
        NSURL *url = [NSURL URLWithString:urlStr];
        NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
        [self.webView loadRequest:request];
    });
}

- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleLightContent;
}

- (void)backAction:(UIButton *)sender {
    [self.navigationController popViewControllerAnimated:YES];
    [self dismissViewControllerAnimated:YES completion:nil];
}

/* 页面加载完成 */
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
    [SVProgressHUD dismiss];
}

/* 页面加载失败 */
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation {
    [SVProgressHUD dismiss];
}

- (WKWebView *)webView{
    if (_webView == nil) {
        
        WKPreferences *pre = [[WKPreferences alloc] init];
        pre.javaScriptEnabled = YES;
        pre.javaScriptCanOpenWindowsAutomatically = YES;
        
        WKWebViewConfiguration *con = [[WKWebViewConfiguration alloc] init];
        con.preferences = pre;
        [con.preferences setValue:@(YES) forKey:@"allowFileAccessFromFileURLs"];
        con.allowsInlineMediaPlayback = YES;
        if (@available(iOS 10.0, *)) {
             [con setValue:@YES forKey:@"allowUniversalAccessFromFileURLs"];
        }
        
        WKUserContentController* uc = [[WKUserContentController alloc] init];
        con.userContentController = uc;
        [uc addScriptMessageHandler:self name:@"shareFn"];
        
        [uc addScriptMessageHandler:self name:@"webClose"];
        
        WKWebView *web = [[WKWebView alloc] initWithFrame:CGRectMake(0,0, kScreenWidth, kScreenHeight) configuration:con];
        web.navigationDelegate = self;
        web.opaque = NO;
        web.backgroundColor = kViewBackgroundColor;
        [self.view addSubview:web];
        _webView = web;
    }
    return _webView;
}

- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message{
    if ([message.name isEqualToString:@"shareFn"]) {
        NSDictionary *dict = message.body;
        /*
         body:{
             fileId = 11;
             fileName = "%E6%96%87%E4%BB%B6";
             type = w;
             urlPage = "https://www.ydl.cool/xx/all-file.html?type=s&userId=945798324";
         }
         */
        NSString *url = dict[@"url"];
        
        //此方法相当于发送一个GET请求，直接将服务器的数据一次性下载下来
        [SVProgressHUD show];
        
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:url]];
            
            NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];
                NSString *fileName = [NSString stringWithFormat:@"/%@",url.lastPathComponent];
                NSString *signDirec = [documentsDirectory stringByAppendingString:fileName];
                
                /// 保存文件到沙盒
                BOOL downResult = [data writeToFile: signDirec atomically:YES];
            
                dispatch_async(dispatch_get_main_queue(), ^{
                   // UI更新代码
                    [SVProgressHUD dismiss];
                    if (downResult) {
                        UIActivityViewController *activityViewController = [[UIActivityViewController alloc] initWithActivityItems:@[[NSURL fileURLWithPath: signDirec]] applicationActivities:nil];
                        [self presentViewController:activityViewController animated:YES completion:nil];
                    }
                });
        });
    } else if ([message.name isEqualToString:@"webClose"]) {
        [self backAction:nil];
    }
}

@end

